package com.datang.yourtomcat02;

import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-09-16 18:22
 * @notify 处理请求servlet
 * @version 1.0
 */

public class ServletProcessor {
    /*
     * @author 顶风少年
     * @date 2019/9/16 22:21
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param request
     * @param response
     * @result void
     * @notify 通过请求的servlet资源名,反射调用servlet
     * version 1.0
     */
    public void process(Request request, Response response) {
        //获取请求servlet路径
        String uri = request.getUri();
        //切割出来servlet名
        String servletName = uri.substring(uri.lastIndexOf("/") + 1);
        //类加载器
        URLClassLoader loader = null;
        try {
            URL[] urls = new URL[1];
            URLStreamHandler streamHandler = null;
            //获取服务端资源路径
            File classPath = new File(Constants.WEB_ROOT);
            String repository = (new URL("file", null, classPath.getCanonicalPath() +
                    File.separator)).toString();

            //创建一个本地文件URL
            urls[0] = new URL(null, repository, streamHandler);
            //获取classloader
            loader = new URLClassLoader(urls);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Class myClass = null;
        try {
            //加载class
            myClass = loader.loadClass(servletName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Servlet servlet = null;
        RequestFacade requestFacade = new RequestFacade(request);
        ResponseFacade responseFacade = new ResponseFacade(response);
        try {
            myClass.newInstance();
            //反射一个servlet实例对象
            servlet = (Servlet) myClass.newInstance();
            //调用service方法
            servlet.service((ServletRequest) requestFacade,
                    (ServletResponse) responseFacade);
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Throwable e) {
           e.printStackTrace();
        }
    }
}
